package com.atguigu.service.impl;

import com.atguigu.pojo.LoginUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class LoginUserService implements UserDetailsService {
    //模拟数据库中的用户数据
    static Map<String, LoginUser> map = new HashMap<String, LoginUser>();

    static {
        LoginUser loginUser =new LoginUser();
        loginUser.setUsername("admin");
        loginUser.setPassword("$2a$10$KAvNNPcmlZkFcsx.vviC/uFLcTuO6hM8/3iAD3TQbaDEBQ05MVcI.\n");
        loginUser.setTelephone("admin123");
        LoginUser loginUser1 = new LoginUser();
        loginUser1.setTelephone("sb123");
        loginUser1.setUsername("sb");
        loginUser1.setPassword("$2a$10$aksgsaR.OHBP1ruRrNaVuuZZVxXrX6HBnkdjbEKec3R1Y3RZlBe22");
        map.put(loginUser.getUsername(), loginUser);
        map.put(loginUser1.getUsername(), loginUser1);
    }
    /**
     * 根据用户名加载用户信息
     *
     * @param username
     * @return
     *
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        System.out.println("username"+username);
        //模拟根据用户名查询数据库
        LoginUser loginUserInDB = map.get(username);

        if (loginUserInDB == null) {
            //根据用户名没有查询到用户，抛出异常，表示用户名输入错误
            return  null;
        }
        //模拟数据库中的密码，后期需要查询数据库
        String  passWordInDb = loginUserInDB.getPassword();

        //授权，后期需要改为拆线呢数据库动态获得用户拥有的权限和角色
        List<GrantedAuthority> lists = new ArrayList<>();
        lists.add(new SimpleGrantedAuthority("add"));
        lists.add(new SimpleGrantedAuthority("delete"));
        lists.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        return new User(username, passWordInDb, lists);
    }
}
